<?php
class Radek {
	
	private $id;
	private $policka = array();
	private $obsazeno = array();
	private $moznosti = array();
	
	function __construct($id,$policka) {
		$this->setId($id);
		$this->setPolicka($policka);
	}
	function setId($id) {
		$this->id=$id;
	}
	
	function getId() {
		return $this->id;
	}
	
	function setPolicka($policka) {
		$this->policka = array();
		foreach ($policka as $key => $value) {
			if($value->getRadek()== $this->getId()){
				$this->policka[]=$value;
			}
		}
	}
	
	function getPolicka() {
		return $this->policka;
	}
	
	function setObsazeno() {
		$this->obsazeno = array();
		foreach ($this->policka as $value) {
			if($value->getCislo() != NULL){
					$this->obsazeno[] = $value->getCislo();
				
			}
		}
	}
	
	function getObsazeno() {
		return $this->obsazeno;
	}
	
	function setMoznosti() {
		$this->moznosti=array();
		for ($i = 1; $i <= 9; $i++) {
			if(!in_array($i,$this->obsazeno)){
				$this->moznosti[]=$i;
			}
		}
		$this->setMoznostiForPolicka();
	}
	
	function getMoznosti() {
		return $this->moznosti;
	}
	
	function setMoznostiForPolicka() {
		foreach ($this->policka as $value) {
			$value->setMoznosti($this->moznosti);
		}
	}
/** Zjistí, zda je číslo na daném políčko jedinou možností, kde může v oblastí být
	 * @param id políčka
	 * @param hledané číslo
	 * @return bool
	 */
	function JedinaMoznost($policko,$cislo) {
		$pole = array();
		foreach ($this->policka as $key => $value) {
			if($value->getCislo() == null and $key != $policko){
				foreach ($value->getMoznosti() as $value) {
					$pole[] = $value;
				}
			}
		}
		$a = array_diff($this->policka[$policko]->getMoznosti(), $pole);
		rsort($a);
		if (count($a)== 1 and $a[0]==$cislo){
			return true;
		}else{
			return false;
		}
	}
	
function NajdiJedineMoznosti() {
		$stav = false;
		foreach ($this->policka as $key => $value) {
				for ($i = 1; $i <= 9; $i++) {
					if ($this->JedinaMoznost($key, $i) and $value->getStav()) {
						$value->setCislo($i);
						$stav = true;
					}
				}
			}
		return $stav;	
		}
		
function PolickoSJedinouMoznosti() {
	$stav = false;	
	foreach ($this->policka as $value) {
			$pole = $value->getMoznosti();
			$pocet = count($pole);
			if ($pocet == 1 and $value->getStav()){
				rsort($pole);
				$value->setCislo($pole[0]);
				$stav = true;
			}
		}
		return $stav;
	}
	
	function JeVyplnen() {
		foreach ($this->policka as $value) {
			if ($value->getStav()) {
				return false;
			}
		}
		return true;
	}
}
?>